package com.red.star.wechat.data.repository;

import com.red.star.wechat.data.entity.PageView;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author nofish.yan@gmail.com
 * @date 2018/8/22.
 * 页面访问记录原数据访问接口
 */
@Repository
public class PageViewRepository {

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 查询当前上一个访问的页面
     * @param fansId 粉丝ID
     * @return 访问记录
     */
    public PageView queryLastRecord(Integer fansId) {
        Query query = Query.query(Criteria.where("fans_id").is(fansId));
        query.with(new Sort(Sort.Direction.DESC, "create_time"));
        return mongoTemplate.findOne(query, PageView.class);
    }

    /**
     * 更新驻留时间
     * @param pageView 访问记录
     * @return 更新数量
     */
    public int updateStayTime(PageView pageView) {
        Query query = Query.query(Criteria.where("_id").is(pageView.getId()));
        Update update = Update.update("update_time", new Date(System.currentTimeMillis()))
                .set("stay_time", pageView.getStayTime());
        return mongoTemplate.updateFirst(query, update, PageView.class).getN();
    }

    /**
     * 保存页面访问记录元数据
     * @param pageView 访问记录
     */
    public void save(PageView pageView) {
        mongoTemplate.save(pageView);
    }
}
